package com.example.xmhds_1.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.xmhds_1.dto.UserChatDTO;
import com.example.xmhds_1.dto.GroupChatDTO;
import com.example.xmhds_1.dto.UserinfoChatDTO;
import com.example.xmhds_1.entity.ChatMessage;
import com.example.xmhds_1.entity.UserInfo;
import com.example.xmhds_1.entity.GroupChat;
import com.example.xmhds_1.mapper.userinfo.ChatMessageMapper;
import com.example.xmhds_1.mapper.userinfo.UserInfoMapper;
import com.example.xmhds_1.mapper.userinfo.GroupChatMapper;
import com.example.xmhds_1.service.ChatService;
import com.example.xmhds_1.utils.Utils;
import com.example.xmhds_1.ws.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 聊天服务实现类
 */
@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private GroupChatMapper groupChatMapper;

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取用户与好友们的最后一条聊天记录
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<UserChatDTO> getUserChatList(String userId) {
        // 获取所有聊天记录
        List<ChatMessage> chatMessages = chatMessageMapper.getMessagesByUser(userId);

        // 收集所有聊天对象的ID
        Set<String> chatUserIds = chatMessages.stream()
                .map(msg -> msg.getUser0().equals(userId) ? msg.getUser1() : msg.getUser0())
                .collect(Collectors.toSet());

        // 构建聊天列表
        return chatUserIds.stream().map(chatUserId -> {
            UserChatDTO dto = new UserChatDTO();

            // 获取聊天对象的用户信息
            UserInfo userInfo = userInfoMapper.selectByAccountId(chatUserId);
            dto.setUserInfo(userInfo);

            // 获取最新的聊天记录
            ChatMessage latestMessage = chatMessageMapper.getMessages(userId, chatUserId);
            if (latestMessage != null && latestMessage.getMessages() != null) {
                JSONArray messageArray = latestMessage.getMessages();
                // 获取最新的几条消息
                int startIndex = Math.max(0, messageArray.size() - 1);

                // 创建新的消息数组，确保每个元素都是JSONObject
                JSONArray latestMessages = new JSONArray();
                for (int i = startIndex; i < messageArray.size(); i++) {
                    Object obj = messageArray.get(i);
                    if (obj instanceof String) {
                        // 如果是字符串，尝试解析为JSONObject
                        try {
                            JSONObject msgObj = JSON.parseObject((String) obj);
                            // 转换为统一的消息格式
                            JSONObject convertedMsg = new JSONObject();
                            convertedMsg.put("from", msgObj.getString("sender"));
                            convertedMsg.put("content", msgObj.getString("content"));
                            convertedMsg.put("time", msgObj.getString("time"));
                            convertedMsg.put("read", msgObj.getBooleanValue("receiverRead"));
                            latestMessages.add(convertedMsg);
                        } catch (Exception e) {
                            log.error("解析消息失败: {}", obj, e);
                            continue;
                        }
                    }
                }
                dto.setLatestMessages(latestMessages);

                // 获取最后一条消息的时间
                if (!latestMessages.isEmpty()) {
                    JSONObject lastMessage = latestMessages.getJSONObject(latestMessages.size() - 1);
                    dto.setLastMessageTime(lastMessage.getString("time"));
                }

                // 计算未读消息数
                dto.setUnreadCount(countUnreadMessages(messageArray, userId));
            }

            return dto;
        }).sorted((a, b) -> {
            // 处理空的lastMessageTime
            String timeA = a.getLastMessageTime();
            String timeB = b.getLastMessageTime();
            if (timeA == null) {
                return 1;
            }
            if (timeB == null) {
                return -1;
            }
            return timeB.compareTo(timeA);
        }).collect(Collectors.toList());
    }

    @Override
    public ChatMessage getChatHistory(String user0, String user1) {
        return chatMessageMapper.getMessages(user0, user1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMessage(String user0, String user1, String message) {
        try {
            // 获取或创建聊天记录
            ChatMessage chatMessage = chatMessageMapper.getMessages(user0, user1);
            if (chatMessage == null) {
                chatMessage = new ChatMessage();
                chatMessage.setUser0(user0);
                chatMessage.setUser1(user1);
                chatMessage.setMessages(new JSONArray());
                chatMessage.setDeleted(0);
            }

            // 构建新消息
            JSONObject newMessage = new JSONObject();
            newMessage.put("sender", user0);
            newMessage.put("content", message);
            newMessage.put("time", LocalDateTime.now().format(formatter));
            newMessage.put("receiverRead", false);
            newMessage.put("senderRead", true);

            // 添加到消息列表
            chatMessage.getMessages().add(newMessage.toJSONString());  // 保存为字符串格式

            // 保存或更新
            if (chatMessage.getId() == null) {
                return chatMessageMapper.insert(chatMessage) > 0;
            } else {
                return chatMessageMapper.updateById(chatMessage) > 0;
            }
        } catch (Exception e) {
            log.error("保存聊天消息失败: ", e);
            return false;
        }
    }

    /**
     * 计算未读消息数量
     */
    private int countUnreadMessages(JSONArray messages, String userId) {
        UserInfo userInfo=userInfoMapper.selectOne(userId);
        int count = 0;
        for (int i = messages.size() - 1; i >= 0; i--) {
            Object obj = messages.get(i);
            if (obj instanceof String) {
                try {
                    JSONObject message = JSON.parseObject((String) obj);
                    if(message.getString("sender").equals(userInfo.getUsername())) {
                        continue;
                    }

                    if (!message.getString("sender").equals(userInfo.getUsername())) {
                        if(message.getBoolean("receiverRead")== false)  {
                            count++;
                        }
                    }
                } catch (Exception e) {
                    log.error("解析消息失败: {}", obj, e);
                }
            }
        }
        return count;
    }

    @Override
    public List<GroupChatDTO> getGroupChatList(String userId) {
        // 1. 获取所有群聊
        List<GroupChat> allGroups = groupChatMapper.getAllGroup();
        //log.info("获取到所有群聊: size={}", allGroups.size());

        // 2. 过滤出用户所在的群聊
        return allGroups.stream()
                .filter(group -> {
                    try {
                        // members字段格式:
                        // [
                        //   {
                        //     "userId": "用户ID",
                        //     "username": "用户名",
                        //     "role": "角色(owner-群主/member-成员)",
                        //     "joinTime": "加入时间",
                        //     "lastReadTime": "最后阅读时间"
                        //   }
                        // ]
                        JSONArray members = group.getMembers();
                        //log.info("群 {} 的成员列表: {}", group.getGroupId(), members);

                        // 遍历成员列表,检查当前用户是否在群中
                        if (members != null) {
                            for (int i = 0; i < members.size(); i++) {
                                JSONObject member = members.getJSONObject(i);
                                if (userId.equals(member.getString("userId"))) {
                                    return true;
                                }
                            }
                        }
                        return false;
                    } catch (Exception e) {
                        log.error("处理群成员失败: groupId={}, members={}",
                                group.getGroupId(), group.getMembers(), e);
                        return false;
                    }
                })
                .map(group -> {
                    GroupChatDTO dto = new GroupChatDTO();
                    dto.setGroupId(group.getGroupId());
                    dto.setGroupName(group.getGroupName());

                    // 处理消息记录
                    JSONArray messages = new JSONArray();
                    try {
                        // messages字段格式:
                        // [
                        //   {
                        //     "sender": "发送者ID",
                        //     "content": "消息内容",
                        //     "time": "发送时间",
                        //     "readUsers": ["已读用户ID1", "已读用户ID2"] // 已读用户列表
                        //   }
                        // ]
                        JSONArray allMessages = group.getMessages();
                        if (allMessages != null && !allMessages.isEmpty()) {
                            // 获取最后一条消息并解析
                            String lastMsgStr = allMessages.getString(allMessages.size() - 1);
                            JSONObject lastMsg = JSON.parseObject(lastMsgStr);

                            // 转换为前端需要的消息格式
                            JSONObject convertedMsg = new JSONObject();
                            convertedMsg.put("from", lastMsg.getString("sender")); // 发送者ID
                            convertedMsg.put("content", lastMsg.getString("content")); // 消息内容
                            convertedMsg.put("time", lastMsg.getString("time")); // 发送时间
                            messages.add(convertedMsg);

                            dto.setLastMessageTime(lastMsg.getString("time"));
                        }
                        dto.setLatestMessages(messages);

                        // 计算未读消息数
                        dto.setUnreadCount(countGroupUnreadMessages(allMessages, userId));
                    } catch (Exception e) {
                        log.error("处理群消息失败: groupId={}", group.getGroupId(), e);
                    }

                    return dto;
                })
                // 按最后消息时间排序，最新的在前面
                .sorted((a, b) -> {
                    String timeA = a.getLastMessageTime();
                    String timeB = b.getLastMessageTime();
                    if (timeA == null) return 1;
                    if (timeB == null) return -1;
                    return timeB.compareTo(timeA);
                })
                .collect(Collectors.toList());
    }


    /**
     * 计算群聊未读消息数
     * 遍历所有消息，统计当前用户未读的消息数量
     */
    private int countGroupUnreadMessages(JSONArray messages, String userId) {
        if (messages == null) return 0;

        int count = 0;
        for (int i = messages.size() - 1; i >= 0; i--) {
            try {
                String msgStr = messages.getString(i);
                JSONObject message = JSON.parseObject(msgStr);

                // 获取发送者ID，如果为空则跳过
                String sender = message.getString("sender");
                if (sender == null) {
                    //log.warn("消息缺少sender字段: {}", message);
                    continue;
                }

                // 如果消息不是由当前用户发送的，且当前用户未读
                if (!sender.equals(userId)) {
                    JSONArray readUsers = message.getJSONArray("readUsers");
                    if (readUsers == null || !readUsers.contains(userId)) {
                        count++;
                    }
                }
            } catch (Exception e) {
                log.error("解析消息失败: {}", messages.getString(i), e);
            }
        }
        return count;
    }
    /**
     * 根据用户的账号和好友的账号查询对应的聊天记录
     */
    @Override
    public List<UserinfoChatDTO> getChatHistoryByUser(String user0, String user1) {
        //根据用户ID查询聊天记录
        ChatMessage chatMessage= getChatHistoryByUser_ChatMessage(user0,user1);
        //将其转换为对应的DTO
        return chatMessage.getMessages_json();
    }
    /**
     * 根据用户的账号和好友的账号修改对应的聊天记录,也就是说将对应的聊天记录变成已读
     */
    @Override
    public void updateChatHistoryByUser(String user0, String user1) {
        ChatMessage chatMessage= getChatHistoryByUser_ChatMessage(user0,user1);
        List<UserinfoChatDTO> messages=chatMessage.getMessages_json(); //获取聊天记录
        for(int i=0;i<messages.size();i++){
            if(!(messages.get(i).getSender().equals(user0))&&messages.get(i).getReceiverRead()==false){
                messages.get(i).setReceiverRead(true);
            }
        }
        //将聊天记录转换为JSON格式
        JSONArray data=chatMessage.getMessages_string(messages);
        chatMessage.setMessages(data);
        //修改聊天记录
        chatMessageMapper.updateById(chatMessage);
    }

    /**
     * 根据用户的账号和好友的账号查询对应的聊天记录
     *
     * @param user0
     * @param user1
     */
    @Override
    public ChatMessage getChatHistoryByUser_ChatMessage(String user0, String user1) {
        //将账号转换为用户ID
        String id_0=userInfoMapper.getUserIdByUsername(user0);
        String id_1=userInfoMapper.getUserIdByUsername(user1);
        if (id_0==null||id_1==null){
            return null;
        }
        //根据用户ID查询聊天记录
        ChatMessage chatMessage= chatMessageMapper.getMessages(id_0,id_1);
        if (chatMessage==null){
            //不存在则创建
            chatMessage=new ChatMessage();
            chatMessage.setUser0(id_0);
            chatMessage.setUser1(id_1);
            chatMessage.setMessages(new JSONArray());
            chatMessageMapper.insert(chatMessage);
        }
        return chatMessage;
    }

    /**
     * 根据用户账号和好友账号,发送信息
     *
     * @param user0
     * @param user1
     * @param message
     */
    @Override
    public boolean setMessages(String user0, String user1, String message) {
        boolean pd=false;
        try {
            //根据user0和user1查询聊天记录
            ChatMessage chatMessage= getChatHistoryByUser_ChatMessage(user0,user1);
            //创建UserinfoChatDTO对象
            UserinfoChatDTO userinfoChatDTO=new UserinfoChatDTO();
            userinfoChatDTO.setSender(user0);
            userinfoChatDTO.setSenderRead(true);
            userinfoChatDTO.setReceiverRead(false);
            userinfoChatDTO.setTime(Utils.getCurrentTimeString());
            userinfoChatDTO.setContent(message);
            //获取List<UserinfoChatDTO>对象
            List<UserinfoChatDTO> messages=chatMessage.getMessages_json();
            messages.add(userinfoChatDTO);
            //将对应的java对象转换为json数组
            JSONArray data=chatMessage.getMessages_string(messages);
            chatMessage.setMessages(data);
            //修改聊天记录
            chatMessageMapper.updateById(chatMessage);
            pd=true;
            //发送通知给在线的接收者
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("type","newMessage");//消息类型
            jsonObject.put("from",user0);//发送者账号
            jsonObject.put("message",message);//消息内容
            jsonObject.put("time",Utils.getCurrentTimeString());//消息时间
            //通过websocket发送通知
            WebSocket.notifyUser(user1,jsonObject.toString());
        }catch (Exception e){
            log.error("发送消息失败",e);
        }
        return pd;
    }
}
